package leetcode.problems;

import org.junit.Test;

/**
 * Created by gmwang on 2018/7/25
 * 单调数组
 */
public class _0731MonotonicArray {
    /**
     *
     * An array is monotonic if it is either monotone increasing or monotone decreasing.
     * 如果单调递增或单调递减，则数组是单调的。
     *
     * An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
     * 如果对于所有i <j，a[i] <＝a[j]，数组A是单调递增的。如果对于所有i <j，a[i]＞a[j]，数组A是单调递减的。
     *
     * Return true if and only if the given array A is monotonic.
     * 当且仅当给定数组A为单调时返回真。
     * Example 1:
     *
     * Input: [1,2,2,3]
     * Output: true
     * Example 2:
     *
     * Input: [6,5,4,4]
     * Output: true
     * Example 3:
     *
     * Input: [1,3,2]
     * Output: false
     * Example 4:
     *
     * Input: [1,2,4,5]
     * Output: true
     * Example 5:
     *
     * Input: [1,1,1]
     * Output: true
     *
     *
     * Note:
     *
     * 1 <= A.length <= 50000
     * -100000 <= A[i] <= 100000
     *
    /**
     * 判断数组前两个元素是增还是减，如果后面违反了这个规则，就返回false
     * @param A
     * @return
     */
    public boolean isMonotonic(int[] A) {
        if(A.length == 0) return false;
        if(A.length == 1 || A.length == 2) return true;
        int flag = 0;   //代表无递增
        for(int i = 1;i<A.length;i++){
            if(A[i] == A[i - 1]) continue;  //相等的话,没有增减性
            if(A[i] >  A[i - 1]) {
                //第一次赋值单调区间
                if(flag == 0){
                    flag = 1;  //单调递增
                }else if(flag == 2){
                    return false;
                }
            }else{
                //第一次赋值单调区间
                if(flag == 0){
                    flag = 2;  //单调递减
                }else if(flag == 1){
                    return false;
                }
            }
        }
        return true;
    }
    @Test
    public void test() {
//        int[] nums = {1,2,2,3};
//        int[] nums = {1,1,1};
//        int[] nums = {6,5,4,4};
        int[] nums = {1,3,2};
        boolean monotonic = isMonotonic(nums);
        System.out.println(monotonic);
    }
}
